package com.gp.common.utils;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.mockito.internal.matchers.EndsWith;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.gp.model.dto.UserAddInfo;
import com.gp.model.entity.AccessLog;
import com.gp.model.entity.BaseUser;
import com.gp.model.entity.BaseUserExtends;

import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.OperatingSystem;
import nl.bitwalker.useragentutils.UserAgent;

/**
 * @author: 弓成龙
 * @date : 2017年12月27日
 * @email : gcx909109@sina.cn
 * @description: cookie操作工具类
 */
public class CookieUtils {

  public static final int COOKIE_MAX_AGE = 7 * 24 * 3600;
  public static final int COOKIE_HALF_HOUR = 60 * 60;
  public static final String SESSION_USER_NAME = "userInfo";
  public static final String SESSION_PERMISSON_NAME = "permissions";

  /**
   * 根据Cookie名称得到Cookie对象，不存在该对象则返回Null
   * 
   * @param request
   * @param name
   * @return
   */
  public static Cookie getCookie(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null || cookies.length == 0) {
      return null;
    }
    Cookie cookie = null;
    for (Cookie c : cookies) {
      if (name.equals(c.getName())) {
        cookie = c;
        break;
      }
    }
    return cookie;
  }

  /**
   * 判断当前的用户是否存在
   * 
   * @param request
   * @return true or false
   */
  public static boolean isExistsCurrentUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    Object currentUser = session.getAttribute(SESSION_USER_NAME);
    return currentUser != null;
  }

  /**
   * 获取当前的用户
   * 
   * @param request
   * @return
   */
  public static Object obtainCurrentUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    return session.getAttribute(SESSION_USER_NAME);
  }

  /**
   * 根据Cookie名称直接得到Cookie值
   * 
   * @param request
   * @param name
   * @return
   */
  public static String getCookieValue(HttpServletRequest request, String name) {
    Cookie cookie = getCookie(request, name);
    if (cookie != null) {
      return cookie.getValue();
    }
    return null;
  }

  /**
   * 移除cookie
   * 
   * @param request
   * @param response
   * @param name 这个是名称，不是值
   */
  public static void removeCookie(HttpServletRequest request, HttpServletResponse response,
      String name) {
    if (null == name) {
      return;
    }
    Cookie cookie = getCookie(request, name);
    if (null != cookie) {
      cookie.setPath("/");
      cookie.setValue("");
      cookie.setMaxAge(0);
      response.addCookie(cookie);
    }
  }

  /**
   * 添加一条新的Cookie，可以指定过期时间(单位：秒)
   * 
   * @param response
   * @param name
   * @param value
   * @param maxValue
   */
  public static void setCookie(HttpServletResponse response, String name, String value,
      int maxValue) {
    if (name == null || name.length() == 0) {
      return;
    }
    if (null == value) {
      value = "";
    }
    Cookie cookie = new Cookie(name, value);
    cookie.setPath("/");
    if (maxValue != 0) {
      cookie.setMaxAge(maxValue);
    } else {
      cookie.setMaxAge(COOKIE_HALF_HOUR);
    }
    response.addCookie(cookie);
    try {
      response.flushBuffer();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 添加一条新的Cookie，默认30分钟过期时间
   * 
   * @param response
   * @param name
   * @param value
   */
  public static void setCookie(HttpServletResponse response, String name, String value) {
    setCookie(response, name, value, COOKIE_HALF_HOUR);
  }

  /**
   * 将cookie封装到Map里面
   * 
   * @param request
   * @return
   */
  public static Map<String, Cookie> getCookieMap(HttpServletRequest request) {
    Map<String, Cookie> cookieMap = new HashMap<String, Cookie>();
    Cookie[] cookies = request.getCookies();
    if (!(cookies == null || cookies.length == 0)) {
      for (Cookie cookie : cookies) {
        cookieMap.put(cookie.getName(), cookie);
      }
    }
    return cookieMap;
  }

  /**
   * 获取session
   * 
   * @param request request 对象
   * @return HttpSession
   */
  public static HttpSession getSession(HttpServletRequest request) {
    if (request == null) {
      request = getCurrentRequest();
    }
    return request.getSession();
  }

  /**
   * @return 当前的reqeust
   */
  public static HttpServletRequest getCurrentRequest() {
    ServletRequestAttributes a =
        (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
    HttpServletRequest request = a.getRequest();
    return request;
  }

  /**
   * 根据request获取访问日志对象
   * 
   * @param request
   * @return AccessLog
   */
  public static AccessLog getAccessLog(HttpServletRequest request) {
    AccessLog log = new AccessLog();
    log.setAccessTime(StringUtil.obtinDateStr(null));
    log.setAccessUrl(request.getRequestURI());
    log.setBrowser(getBrowser(request));
    log.setUserAgent(request.getHeader("User-Agent"));
    log.setIP(getIpAddr(request));
    BaseUser user = (BaseUser) obtainCurrentUser(request);
    log.setSourceUrl(request.getHeader("referer"));
    log.setSessionId(request.getSession().getId());
    if(request.getRequestURI().endsWith(".html")){
      log.setUrlLevel(0);
    }else {
      log.setUrlLevel(1);
    }
    if (user != null) {
      log.setPhoneno(user.getPhone()+"");
      log.setUsername(user.getNickName()+"");
      log.setUserId(user.getId()+"");
    }
    return log;
  }

  /**
   * 获取ip
   *
   * @param request
   * @return
   * @throws Exception
   */
  public static final String getIpAddr(final HttpServletRequest request) {
    String ip = request.getHeader("x-forwarded-for");
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("WL-Proxy-Client-IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_CLIENT_IP");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getHeader("HTTP_X_FORWARDED_FOR");
    }
    if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
      ip = request.getRemoteAddr();
    }
    // 多个路由时，取第一个非unknown的ip
    final String[] arr = ip.split(",");
    for (final String str : arr) {
      if (!"unknown".equalsIgnoreCase(str)) {
        ip = str;
        break;
      }
    }
    return ip;
  }

  /**
   * 填写用户的默认信息
   * 
   * @param user
   */
  public static void getRequestInfo(BaseUser user) {
    user.setUserType(0);
    user.setAuditState(0);
    user.setCreateTime(new Date());
    user.setLastLoginIP(getIpAddr(getCurrentRequest()));
    user.setLastLoginTime(new Date());
  }
  
  /**
   * 根据用户详细信息设置用户信息
   * 
   * @param user
   */
  public static BaseUser getSimpleUserInfo(UserAddInfo user) {
    BaseUser u = new BaseUser();
    user.setUserType(user.getUserType());
    u.setAuditState(user.getAuditStatus());
    u.setCreateTime(new Date());
    u.setNickName(user.getNickName());
    u.setPhone(user.getPhone());
    u.setUserType(user.getUserType());
    u.setLoginName(user.getLoginName());
    u.setLoginPassword(user.getLoginPassword());
    u.setState(user.getState());
    u.setGender(user.getGender());
    return u;
  }
  
  public static BaseUserExtends getUserDetailInfo(Object id, UserAddInfo user) {
    BaseUserExtends e = new BaseUserExtends();
    e.setBirthday(user.getBirthday());
    e.setCountMany(user.getCountMoney());
    e.setEmail(user.getEmail());
    e.setIdCard(user.getIdCard());
    e.setTradePassword(user.getTradePassword());
    e.setUserId(Long.parseLong(id+""));
    return e;
  }

  /**
   * 获取浏览器类型
   * 
   * @param request
   */
  public static String getBrowser(HttpServletRequest request) {
    request = request == null ? getCurrentRequest() : request;
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    Browser browser = userAgent.getBrowser();
    return browser.getName();

  }

  /**
   * 获取操作系统
   * 
   * @param request
   */
  public static String getOS(HttpServletRequest request) {
    request = request == null ? getCurrentRequest() : request;
    UserAgent userAgent = UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
    OperatingSystem os = userAgent.getOperatingSystem();
    return os.getName();
  }
  
  /**
   * 设置用户到session中
   * @param request
   * @param user
   */
  public static void setUser(HttpServletRequest request, BaseUser user) {
    HttpSession session = request.getSession();
    session.setAttribute(SESSION_USER_NAME, user);
  }
  
  /**
   * 将用户从session中删除
   * @param request
   */
  public static void removeUser(HttpServletRequest request) {
    HttpSession session = request.getSession();
    session.removeAttribute(SESSION_USER_NAME);
  }


}
